<?php

namespace Biz\service\course;

use Biz\model\course\Chapter as mChapter;
use Biz\model\course\Course as mCourse;
use Biz\model\course\CourseEvaluation as mCourseEvaluation;
use Biz\model\course\CourseExtend as mCourseExtend;
use Biz\model\course\CourseLog as mCourseLog;
use Doraemon\model\Videos as mVideos;
use Doraemon\service\User;
use Doraemon\service\Videos\Videos;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;

class AdmCourse
{
    public static function getCourseList($where)
    {
        $list = mCourse::selectByWhere($where);
        foreach ($list as &$row) {
            $row['id'] = $row['course_id'];
            $row['status_desc'] = mCourse::STATUS_DESC[$row['course_status']];
            $row['h5_url'] = Hhzurl::h5ShareCourse($row['course_id']);
            $row['spec_img'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $row['spec_img'], ImgUrl::IMAGE_SIZE_OP_ORI);
            $row['duration'] = self::changeTimeType($row['duration']);
        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = mCourse::selectCount($where);
        return ['list' => $list, 'total' => $count];
    }

    /**
     * 获取推荐课程
     */
    public static function getRecommend()
    {
        $where = [
            'course_status' => mCourse::STATUS_ONLINE,
            'ORDER' => ['sort' => 'ASC', 'course_id' => 'ASC']
        ];
        $list = mCourse::selectByWhere($where);
        foreach ($list as &$row) {
            $row['id'] = $row['course_id'];
            $row['duration'] = self::changeTimeType($row['duration']);
            $row['status_desc'] = mCourse::STATUS_DESC[$row['course_status']];
            $row['h5_url'] = Hhzurl::h5ShareCourse($row['course_id']);
            $row['spec_img'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $row['spec_img'], ImgUrl::IMAGE_SIZE_OP_ORI);
        }
        return $list;
    }

    public static function sort($sort, $id)
    {
        mCourse::updateData(['sort' => $sort], ['course_id' => $id]);
    }

    public static function getCourseEvaluation($where)
    {
        if (!HhzEnv::isShopHaoHaoCe()) {
            $where['course_id[!]'] = [1, 2, 4, 5, 6, 8];
        }
        $list = mCourse::selectByWhere($where);
        $courseIds = array_column($list, 'course_id');
        $evaluationList = mCourseEvaluation::getCourseAvgStar($courseIds);
        foreach ($list as &$row) {
            $evaluationInfo = isset($evaluationList[$row['course_id']]) ? $evaluationList[$row['course_id']] : [];
            $row['id'] = $row['course_id'];
            $row['status_desc'] = mCourse::STATUS_DESC[$row['course_status']];
            $row['course_start'] = $evaluationInfo ? round($evaluationInfo['course_start'], 2) : 0;
            $row['teacher_start'] = $evaluationInfo ? round($evaluationInfo['teacher_start'], 2) : 0;
            $row['ue_start'] = $evaluationInfo ? round($evaluationInfo['ue_start'], 2) : 0;

        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = mCourse::selectCount($where);
        return ['list' => $list, 'total' => $count];
    }

    public static function getEvaluationList($where)
    {
        $list = mCourseEvaluation::selectByWhere($where);
        $courseIds = array_column($list, 'course_id');
        $uids = array_column($list, 'uid');
        $uids = array_unique($uids);
        $userList = User::getBatchBasicUserInfo($uids);
        $userList = array_column($userList, null, 'uid');
        $courseList = mCourse::selectByWhere(['course_id' => $courseIds]);
        $courseList = array_column($courseList, null, 'course_id');
        foreach ($list as &$row) {
            $courseInfo = isset($courseList[$row['course_id']]) ? $courseList[$row['course_id']] : [];
            $userInfo = isset($userList[$row['uid']]) ? $userList[$row['uid']] : [];
            $row['course_title'] = $courseInfo ? $courseInfo['title'] : '';
            $row['nick'] = $userInfo ? $userInfo['nick'] : '';
        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = mCourseEvaluation::selectCount($where);
        return ['list' => $list, 'total' => $count];
    }

    public static function getCourseInfo($courseId)
    {
        $info = mCourse::getByWhere(['course_id' => $courseId, 'course_status[!]' => mCourse::STATUS_DELETE]);
        if ($info['receive_link']) {
            $linkArr = json_decode($info['receive_link'], true);
            $info['receive_link'] = $linkArr['link'];
            $info['receive_pwd'] = $linkArr['pwd'];
        }
        if ($info) {
            $extendInfo = mCourseExtend::getByWhere(['course_id' => $courseId]);
            $info['content'] = $extendInfo ? $extendInfo['content'] : '';
        }
        return $info;
    }

    public static function getChapterList($courseId)
    {
        $where = ['course_id' => $courseId, 'chapter_status' => mChapter::STATUS_NORMAL, 'ORDER' => ['sort' => 'ASC', 'id' => 'ASC']];
        $list = mChapter::selectByWhere($where);
        $videoIds = array_column($list, 'video_id');
        $videoIds = array_filter($videoIds);
        $videoList = Videos::getCanUseVideoInfosByIds($videoIds);
        $isChangeDuration = false;
        foreach ($list as &$row) {
            $videoInfo = isset($videoList[$row['video_id']]) ? $videoList[$row['video_id']] : [];
            $videoUrl = $videoInfo ? $videoInfo['play_url'] : '';
            $picUrl = $videoInfo ? $videoInfo['pic_url'] : '';
            $duration = $videoInfo ? $videoInfo['duration'] : 0;
            if ($row['duration'] != $duration) {
                $row['duration'] = $duration;
                $isChangeDuration = true;
                mChapter::updateData(['duration' => $duration], ['id' => $row['id']]);
            }
            $row['duration'] = self::changeTimeType($row['duration']);
            $row['pic_url'] = $picUrl;
            $row['video_url'] = $videoUrl;
        }
        if ($isChangeDuration) {
            self::changeChapterNumAndDuration($courseId);
        }
        return $list;
    }

    public static function getChapterInfo($chapterId)
    {
        $info = mChapter::getByWhere(['id' => $chapterId, 'chapter_status' => mChapter::STATUS_NORMAL]);
        return $info;
    }

    public static function addCourseInfo($data, $courseId = 0, $adminId = 0)
    {
        $operateType = $courseId ? mCourseLog::OPERATE_TYPE_EDIT : mCourseLog::OPERATE_TYPE_CREATE;
        $result = mCourse::action(function () use ($data, &$courseId, $adminId) {
            $courseData = $data;
            unset($courseData['content']);
            $isChange = false;
            if ($courseId) {
                $isChange = true;
                $result = mCourse::updateData($courseData, ['course_id' => $courseId]);
            } else {
                $result = mCourse::insertData($courseData);
                $courseId = $result;
            }
            if ($result && $courseId) {
                if ($isChange) {
                    $extendData = [
                        'content' => $data['content'],
                    ];
                    $result = mCourseExtend::updateData($extendData, ['course_id' => $courseId]);
                } else {
                    $extendData = [
                        'course_id' => $courseId,
                        'content' => $data['content'],
                    ];
                    $result = mCourseExtend::insertData($extendData);
                }
                if (!$result) {
                    throw new \Exception('操作数据失败');
                }
                return true;
            } else {
                throw new \Exception('操作数据失败');
            }
        });
        if ($result) {
            self::addCourseLog($courseId, $operateType, $data, $adminId);
        }
        return $result;
    }

    public static function offlineCourse($courseId, $adminId = 0)
    {
        $result = mCourse::updateData(['course_status' => mCourse::STATUS_OFFLINE], ['course_id' => $courseId]);
        if ($result) {
            self::addCourseLog($courseId, mCourseLog::OPERATE_TYPE_OFFLINE, ['course_status' => mCourse::STATUS_OFFLINE], $adminId);
        }
        return $result;
    }

    public static function onlineCourse($courseId, $adminId = 0)
    {
        $count = mChapter::selectCount(['course_id' => $courseId, 'chapter_status' => mChapter::STATUS_NORMAL]);
        if (!$count || empty($count)) {
            throw new \Exception('请先添加课程章节');
        }
        $result = mCourse::updateData(['course_status' => mCourse::STATUS_ONLINE, 'online_time' => date('Y-m-d H:i:s')], ['course_id' => $courseId]);
        if ($result) {
            self::addCourseLog($courseId, mCourseLog::OPERATE_TYPE_ONLINE, ['course_status' => mCourse::STATUS_ONLINE], $adminId);
        }
        return $result;
    }

    public static function addChapter($data, $id = 0, $adminId = 0)
    {
        $courseId = $data['course_id'];
        $videoId = $data['video_id'];
        $videoInfos = mVideos::getCommunityBackgroundVideosByIds([$videoId]);
        $videoInfo = $videoInfos ? array_shift($videoInfos) : [];
        $data['duration'] = $videoInfo ? $videoInfo['duration'] : 0;
        if ($id) {
            $result = mChapter::updateData($data, ['id' => $id]);
            $operateType = mCourseLog::OPERATE_TYPE_EDIT_CHAPTER;
        } else {
            $result = mChapter::insertData($data);
            $id = $result;
            $operateType = mCourseLog::OPERATE_TYPE_ADD_CHAPTER;
        }
        $data['chapter_id'] = $id;
        if ($result) {
            $arr = self::changeChapterNumAndDuration($courseId); //更新章节数量及时长
            $chapterNum = $arr['chapter_num'];
            $duration = $arr['duration'];
            $isTry = $arr['is_try'];
            $operateData = $data;
            $operateData['chapter_id'] = $id;
            $operateData['course_chapter_num'] = $chapterNum;
            $operateData['course_duration'] = $duration;
            $operateData['is_try'] = $isTry;
            self::addCourseLog($courseId, $operateType, $operateData, $adminId);
            mVideos::updateStatus($videoId, mVideos::STATUS_NORNAL);
        }
        return $result;
    }

    public static function delChapter($courseId, $chapterId, $adminId = 0)
    {
        $chapterInfo = mChapter::getByWhere(['id' => $chapterId]);
        $result = mChapter::updateData(['chapter_status' => mChapter::STATUS_DELETE], ['course_id' => $courseId, 'id' => $chapterId]);
        if ($result) {
            $arr = self::changeChapterNumAndDuration($courseId); //更新章节数量及时长
            $chapterNum = $arr['chapter_num'];
            $duration = $arr['duration'];
            $isTry = $arr['is_try'];
            $operateData = [
                'chapter_id' => $chapterId,
                'chapter_status' => mChapter::STATUS_DELETE,
                'course_chapter_num' => $chapterNum,
                'course_duration' => $duration,
                'is_try' => $isTry
            ];
            mVideos::updateStatus($chapterInfo['video_id'], mVideos::STATUS_DELETE);
            self::addCourseLog($courseId, mCourseLog::OPERATE_TYPE_DEL_CHAPTER, $operateData, $adminId);
        }
        return $result;
    }

    /**
     * 更新课程章节数量及时长
     * @param $courseId
     * @return array 课程的章节数量及时长
     */
    private static function changeChapterNumAndDuration($courseId)
    {
        $list = mChapter::select_master('*', ['course_id' => $courseId, 'chapter_status' => mChapter::STATUS_NORMAL]);
        $duration = 0;
        $isTry = 0;
        foreach ($list as $row) {
            $duration += $row['duration'];
            if ($row['is_try']) {
                $isTry = 1;
            }
        }
        $count = count($list);
        mCourse::updateData(['chapter_num' => $count, 'duration' => $duration, 'is_try' => $isTry], ['course_id' => $courseId]);
        return ['chapter_num' => $count, 'duration' => $duration, 'is_try' => $isTry];
    }

    /**
     * 操作日志
     * @param $courseId
     * @param $operateType
     * @param $operateData
     * @param int $adminUid
     */
    public static function addCourseLog($courseId, $operateType, $operateData, $adminUid = 0)
    {
        $data = [
            'course_id' => $courseId,
            'operate_type' => $operateType,
            'operate_data' => is_array($operateData) ? json_encode($operateData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : $operateData,
            'operate_time' => date('Y-m-d H:i:s'),
            'operate_admin' => $adminUid
        ];
        mCourseLog::insertData($data);
    }

    public static function changeVideoInfo($videoId)
    {
        $list = mChapter::selectByWhere(['video_id' => $videoId]);
        $ids = array_column($list, 'id');
        $courseIds = array_column($list, 'course_id');
        $courseIds = array_unique($courseIds);
        $videoInfos = mVideos::getCommunityBackgroundVideosByIds([$videoId]);
        $videoInfo = $videoInfos ? array_shift($videoInfos) : [];
        $duration = $videoInfo ? $videoInfo['duration'] : 0;
        Log::debug('update duration#video_id:' . $videoId, ['chapter_ids' => $ids, 'duration' => $duration, 'course_ids' => $courseIds]);
        foreach ($ids as $id) {
            mChapter::updateData(['duration' => $duration], ['id' => $id]);
        }
        foreach ($courseIds as $courseId) {
            self::changeChapterNumAndDuration($courseId);
        }
    }

    private static function changeTimeType($seconds)
    {
        if ($seconds > 3600) {
            $hours = intval($seconds / 3600);
            $time = $hours . ":" . gmstrftime('%M:%S', $seconds);
        } else {
            $time = gmstrftime('%H:%M:%S', $seconds);
        }
        return $time;
    }

}